package com.atzly.community.service.impl;

import com.atzly.community.service.AccessCountService;
import com.atzly.community.utils.RedisKeyUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author zlysimida
 * @date 2021/9/4 - 6:55
 */
@Service
public class AccessCountServiceImpl implements AccessCountService {

    @Autowired
    private RedisTemplate redisTemplate;

    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    @Override
    public void recordUV(String ip) {
        String uvKey = RedisKeyUtils.getUvKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(uvKey, ip);
    }

    @Override
    public long countManyDaysUv(Date startDate, Date endDate) {
        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        // 整理日期范围并每一天的key进行查找
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);

        // 统计天数key
        while (!calendar.getTime().after(endDate)) {
            String uvKey = RedisKeyUtils.getUvKey(df.format(calendar.getTime()));
            keyList.add(uvKey);
            // 将当前天数加一
            calendar.add(Calendar.DATE, 1);
        }
        // 合并
        String redisKey = RedisKeyUtils.getDauKey(df.format(startDate), df.format(endDate));
        redisTemplate.opsForHyperLogLog().union(redisKey, keyList.toArray());

        // 返回合并结果
        return redisTemplate.opsForHyperLogLog().size(redisKey);
    }

    @Override
    public void recordDAU(int userId) {
        String dauKey = RedisKeyUtils.getDauKey(df.format(new Date()));
        // 在第userId位存储该用户登录访问过该网站
        redisTemplate.opsForValue().setBit(dauKey, userId, true);
    }

    @Override
    public long countManyDaysDau(Date startDate, Date endDate) {

        if (startDate == null || endDate == null) {
            throw new IllegalArgumentException("参数不能为空!");
        }

        List<byte[]> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(startDate);
        while (!calendar.getTime().after(endDate)) {
            String key = RedisKeyUtils.getDauKey(df.format(calendar.getTime()));
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE, 1);
        }
        // 统计区间dau
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                String redisKey = RedisKeyUtils.getDauKey(df.format(startDate), df.format(endDate));
                // 对多个位图进行或or运算
                connection.bitOp(RedisStringCommands.BitOperation.OR,
                        redisKey.getBytes(), keyList.toArray(new byte[0][0]));

                return connection.bitCount(redisKey.getBytes());
            }
        });
    }
}
